// 生产路径
var baseUrl = './static/newPhone/';
// 本地路径
// var baseUrl = './';
require.config({
    baseUrl: baseUrl + "lib",
    paths: {
        "jquery": ["jquery"],
        "scrollbar": ["scrollbar"],
        "phoPanel": ["phoPanel"],
        "iconfont": ["iconfont"],
        "phone": ["phone"]
    }
})
require(["jquery", "phone", "scrollbar", "phoPanel", "iconfont"], function ($) {
    var menusArr = [
        'btn_login', //登入
        'btn_logout', //登出
        'btn_ready', //置闲
        'btn_notready', //置忙
        'btn_answer', //接听
        'btn_disconnect', //挂断
        'btn_callout', //外呼
        'btn_holdon', //坐席被保持
        'btn_callback', //接回 ？ 调的是retrive
        'btn_consult', //咨询
        'btn_transfer', //转接 //btn_retrive
        'btn_meet', //会议
        'btn_monitor', //监听
        'btn_drop', //强拆？
        'btn_insert', //强插
        // 'btn_suspended', //保持 ? 强插 ? 15 客户被保持
        'btn_cooperation', //坐席协作
        'btn_reset', //重置
        'btn_set', //设置
        // 2021/2/21 add start
        'btn_transferIvr', //转回IVR
        'btn_transferSkill', //转技能组
        'btn_step_meet', //单步会议
        'btn_startmute', //静音
        'btn_endmute', //取消静音
        // 2021/2/21 add end
        'btn_whisper', //密语
        'btn_degree' //转满意度
    ]
    var oldState = {};
    var newState = {};
    var oldStateTxt = '置忙';
    var newStateTxt = '置忙';
    var curNotReadyTxt = '置忙';
    var timer = null,
        s = 0; // 计时显示
    var stateBgColors = [{
            state: '置忙',
            bgColor: '#dd3256'
        },
        {
            state: '置闲',
            bgColor: '#82be3f'
        },
        {
            state: '保持中',
            bgColor: '#d9a805'
        },
        {
            state: '通话中',
            bgColor: '#04c3e7'
        },
        {
            state: '振铃中',
            bgColor: '#d86109'
        },
        {
            state: '咨询中',
            bgColor: '#80c35a'
        },
        {
            state: '监听中',
            bgColor: '#4a85c8'
        },
        {
            state: '会议中',
            bgColor: '#5fc29b'
        }
    ];
    /*
     * 获取到states 变化量
     */
    var getNewStates = function (oldState, newState) {
        var obj = {};
        if (JSON.stringify(oldState) === "{}") {
            return newState
        } else {
            menusArr.forEach(function (item) {
                if (oldState[item] !== newState[item]) {
                    obj[item] = newState[item]
                }
            })
            return obj;
        }
    }

    /*
     * 获取到外显号并完成渲染
     */
    function explicitNumRender(data) {
        $('.callingNumberList').html('');
        if (data.Result === -1) return;
        data.split(',').forEach(function (e) {
            if (e != '') {
                if (e.indexOf('tel:') == 0 || e.indexOf('sip:') == 0) {
                    $('.callingNumberList').append('<li>' + e.substring(4) + '</li>');
                }
            }
        });
    }
    /*
     * 状态改变渲染函数
     */
    function updateStateRender(states, stateTxt, callBackData) {
        console.log('states:::::::::::::::')
        console.dir(states)
        // state 所有的值
        var $p = $('.phonebarstate>p'); // 置闲置忙显示
        var $ul = $('.phonebarstate>ul'); // 状态切换面板
        var $hold = $('.pho-state-change>.font1'); // 保持接回 显示
        var $answer = $(".phonebar>li:nth-child(1)"); // 接听 挂断 显示
        if (stateTxt) {
            if (stateTxt !== '置忙') { // 因为置忙全部换成小状态 了 stateTxt === '置忙': 代表置忙状态成立
                $p.text(stateTxt); // 有可能是 通话中、咨询中 等
                // 置闲 第一个不显示
                if (stateTxt === '置闲') {
                    $ul.find('li:first-child').hide();
                    $ul.find('li:not(:first-child)').show();
                    $('.phonebarstate').css('backgroundColor', '#82be3f')
                } else if (stateTxt === '整理') { // 整理 都显示
                    $ul.find('li').show();
                } else {
                    $ul.find('li').hide(); // 其他 都不显示
                }
            } else {
                $p.text(curNotReadyTxt); // curNotReadyTxt 小状态接口中获取到的 小状态字段
                $ul.find('li:first-child').show(); // 只显示第一个
                // $ul.find('li:not(:first-child)').hide();
                $ul.find('li:not(:first-child)').each(function () {
                    if ($(this).text() === curNotReadyTxt) {
                        $(this).hide();
                    }
                })
                $('.phonebarstate').css('backgroundColor', '#dd3256');
            }
            newStateTxt = stateTxt;
            handleTiming(oldStateTxt, newStateTxt, callBackData);
            oldStateTxt = stateTxt;
            // 可能有问题
            if (stateTxt === '整理') {
                $(".pho-state>ul>li:nth-child(1)").html('暂无通话')
            }
            if (stateTxt === '保持中') {
                $answer.removeClass().addClass("iconfont icon-wutonghua");
            }
        }
        var arr = Object.keys(states);
        arr.forEach(function (item, index) {
            //注意保持和接回是同一个按钮 btn_holdon
            var $item = $('.' + item);
            if (states[item] === 1) { // calling
                if (item === 'btn_holdon') {
                    $hold.text('保持');
                } else if (item === 'btn_callback') {
                    $hold.text('接回');
                }
                if ($item[0] && $item.attr('class').indexOf('calling') === -1) { // 如果没有calling
                    $item.addClass('calling')
                }
                // 登出 外呼 接听 挂断 振铃 单独处理
                if (item === 'btn_answer') { // 可接听 显示振铃
                    $answer.removeClass().append('<img src="' + baseUrl + './images/calling.gif" style="width:30px;height:30px;border-radius:4px">');
                } else if (item === 'btn_disconnect') { // 可挂断 显示挂断
                    $answer.children().remove();
                    $answer.removeClass().addClass("iconfont icon-guaduan allowed");
                    // $answer.css('cursor','pointer');
                } else if (item === 'btn_logout' || item === 'btn_ready' || item === 'btn_notready') {
                    $answer.children().remove();
                    $answer.removeClass().addClass("iconfont icon-wutonghua");
                } else if (item === 'btn_logout') {
                    $answer.children().remove();
                    $answer.removeClass().addClass("iconfont icon-wutonghua");
                }
            } else {
                console.log('值时0 的按钮')
                if ((item !== 'btn_holdon' && item !== 'btn_callback') || (item === 'btn_holdon' && $hold.text() === '保持') || (item === 'btn_callback' && $hold.text() === '接回')) {
                    if ($item[0] && $item.attr('class').indexOf('calling') !== -1) {
                        $item.removeClass('calling');
                    }
                }
            }
        })
    }
    /*
     * 计时器样式
     */
    var isHoldStatus = "0";

    function handleTiming(oldStateTxt, newStateTxt, callBackData) {
        var $span = $('.phonebarstate>span');
        var $phonebarstate = $('.phonebarstate');
        if (oldStateTxt !== newStateTxt) {
            // 更新状态背景
            var bgColorObj = stateBgColors.find(function (elem) {
                return elem.state === newStateTxt
            })
            if (bgColorObj) {
                $phonebarstate.css("background", bgColorObj['bgColor'])
            } else {
                $phonebarstate.css("background", '#e83333');
            }
            // if (newStateTxt === '振铃中' || newStateTxt === '通话中' || newStateTxt === '咨询中' || newStateTxt === '保持中' || newStateTxt === '会议中' || newStateTxt === '监听中') {
            if (newStateTxt === '振铃中' || newStateTxt === '通话中' || newStateTxt === '监听中') {
                // 关掉旧计时
                // 开启新计时
                // 重新计时
                if (isHoldStatus == "1") {
                    isHoldStatus = "0";
                    return;
                }
                clearInterval(timer);
                var s;
                // console.log('AgentStateTime' in callBackData);
                // console.log(callBackData.hasOwnProperty('AgentStateTime'));
                // console.log(callBackData['AgentStateTime']);
                if (callBackData.hasOwnProperty('AgentStateTime')) {
                    //     // 时间转分秒数 2019/6/12 11:04:32
                    s = parseInt((new Date().getTime() - new Date(callBackData['AgentStateTime']).getTime()) / 1000);
                } else {
                    s = 0;
                }
                timer = null;
                timer = setInterval(function () {
                    s++;
                    var h = parseInt(s / 3600);
                    h < 10 && (h = "0" + h);
                    var m = parseInt(s % 3600 / 60);
                    m < 10 && (m = "0" + m);
                    var S = s % 60;
                    S < 10 && (S = "0" + S);
                    $span.html('<span class="callcolor" style="color:white;"><b id="ptime">' + m + ':' + S + '</b></span>');
                }, 1000)
            } else if (newStateTxt === '咨询中' || newStateTxt === '保持中' || newStateTxt === '会议中') {
                isHoldStatus = "1";
            } else {
                clearInterval(timer);
                s = 0;
                isHoldStatus = "0";
                timer = null;
                $span.html('--:--:--');
            }
        }
    }
    /*
     * 登陆中渲染函数
     */
    function loginingRender() {
        // 登录进行中渲染
        $phoarraybox.show();
        $logining.show();
    }
    /*
     * 用户自定义 登陆之后渲染函数
     * res为1 则登录成功 res为0 则登录失败
     */
    function loginRender(res) {
        // 登录成功渲染
        if (res.Code === '0') {
            // 登录成功渲染
            $logining.hide(1000);
            $unknownTip.hide(500);
            $phonebar.show(1000);
        } else {
            // 登陆失败渲染
            $logining.hide(1000);
            $loginfail.show(1000);
            $unknownTip.show(500, function () {
                $unknownTip.find('p').text(res.Msg);
            });
        }
    }

    function logoutRender() {
        // 登出成功渲染
        $phonebar.hide(1000);
        $loginfail.hide(1000);
    }

    function smallStatusRender(arr) {

        // 小状态 显示
        if (typeof arr === 'object' && arr.length > 0) {
            var i = 0;
            var leng = arr.length;
            var tempHtmlArr = [];
            $('#Statelist>li:not(:first-child)').remove();
            // $('#Statelist>li:first-child').after('<li data-type="self"><i class="iconfont icon-zaixian"></i><a href="#">置忙</a></li>');
            for (i; i < leng; i++) {
                var liHtmlCode = '<li data-statusCode = ' + arr[i].statusCode + '><i class="iconfont icon-xiaoxiu"></i><a href="">' + arr[i].statusName + '</a></li>';
                tempHtmlArr.push(liHtmlCode);
            }

            $('#Statelist').append(tempHtmlArr.join(''));
            $('.phonebarstate').find('p').text(arr[0].statusName);
            curNotReadyTxt = arr[0].statusName;
        } else {
            $('#Statelist>li:not(:first-child)').remove();
            $('#Statelist>li:first-child').after('<li data-type="self"><i class="iconfont icon-manglu"></i><a href="#">置忙</a></li>');
        }
    }
    /*
     * 用户配置可使用菜单
     */
    var phone = new window.newPhone();
    phone.config.menus = menusArr.concat([]);
    /*
     * 用户传入渲染函数 顺序不能错
     */
    phone.defineRenderFn(loginingRender, loginRender, explicitNumRender, logoutRender, smallStatusRender);
    /*
     * 用户传入接收状态函数
     */
    phone.getStates(function (states, stateTxt, callBackData) {
        if (typeof states === 'object') {
            //拿到值重新渲染menus; states 是 对象
            newState = Object.assign({}, states);
            var newStates = getNewStates(oldState, newState);
            console.log('变化后state')
            console.dir(newStates)
            oldState = Object.assign({}, newState);
            updateStateRender(newStates, stateTxt, callBackData); // 变化后的状态进行渲染
        } else if (states === 404) {
            $('.loginfail').text('电话因uc service停止服务被迁出，可尝试重新登录').show();
        } else if (states === -1) {
            return;
        }
        if (callBackData) {
            if (callBackData.EventType === 'AgentStatus_Unkown') {
                $unknownTip.show(500, function () {
                    $unknownTip.find('p').text(callBackData.AgentMessage);
                });
            } else {
                $unknownTip.hide(500);
            }
            $('#textarea').html('');
            $.each(callBackData, function (index, item) {
                $('#textarea').append('<li><span>' + index + ':</span>' + item + '</li>')
            })
        }
    })
    /*
     * 用户传入弹屏处理函数
     */
    phone.getAlertScreenFn(function () {
        var data = arguments[0];
        var state = arguments[1];
        var isNeedAlert = arguments[2];
        var showPhoneNum = '';
        if (state === 0) { // 0是外呼
            var ServiceDirect = 3;
            showPhoneNum = data.DNIS.substring(4);
            alertScreen(data, data.ANI.substring(4), data.DNIS.substring(4), ServiceDirect, isNeedAlert);
        } else {
            if (/^tel:/ig.test(data.ANI)) {
                data.ANI = data.ANI.substring(4);
            } // 1 是内呼
            showPhoneNum = data.ANI;
            var ServiceDirect = 0;
            alertScreen(data, data.DNIS, data.ANI, ServiceDirect, isNeedAlert);
        }
        if (showPhoneNum.length === 11) {
            showPhoneNum = showPhoneNum.slice(0, 3) + '****' + showPhoneNum.slice(7);
        }
        $(".pho-state>ul>li:nth-child(1)").text(showPhoneNum);
    })
    /*
     * 弹屏事件
     */
    function alertScreen(data, ANI, DNIS, ServiceDirect, isNeedAlert) {
        // ****  弹屏事件开始  *********
        // ****  弹屏事件开始  *********
        var tempObj = {
            'SessionID': data.SessionID,
            'ANI': ANI,
            'DNIS': DNIS,
            'EventType': data.EventType,
            'CallType': data.CallType,
            'IVRData': data.IVRData
        }
        if (isNeedAlert === false) {
            tempObj['isNeedAlert'] = false;
        }
        // if (tempObj.CallType !== 'OUTBOUND') {
        //     var temp = tempObj.DNIS;
        //     tempObj.DNIS = tempObj.ANI;
        //     tempObj.ANI = temp;
        // }
        // $('.side_bar')[0].__vue__.$refs.callBar[0].$el.click();
        // getChildCallBarFun(tempObj);
        phoneUserInfo.alertScreen(tempObj);
        // ****  弹屏事件结束  *********
    }
    /*
     *
     */
    var userInfo = window.phoneUserInfo;
    phone.create();
    // 将phone 暴出
    window.phone = phone;
    /*
     * 用户进行事件绑定
     */

    $('.btn_login').click(function () {
        // 登录的时候传值放置
        // phone.loginConfig.password = $.md5(userInfo.password).toUpperCase();
        phone.loginConfig.password = userInfo.password;
        phone.loginConfig.agentID = userInfo.agentID;
        phone.loginConfig.entId = userInfo.entId;
        phone.loginConfig.sipUser = userInfo.sipUser;
        phone.loginConfig.TerminalType = userInfo.TerminalType;
        // phone.loginConfig.httpServerAddress = ucHttpServerAddress ? ucHttpServerAddress : userInfo.httpServerAddress;
        phone.defineEvent('btn_login');
    })

    $('.btn_logout').click(function () {
        phone.defineEvent('btn_logout');
    })
    /*
     * 加载css
     */
    var scriptarr = [
        '<link type="text/css" rel="stylesheet" href="' + baseUrl + './css/phonebar.css">'
    ];
    scriptarr = scriptarr.join('');
    $("head").append(scriptarr);
    /*
     * 加载DOM
     */
    var phoarray = [
        '<div  class="phoarraybox" style="z-index:9999">',
        '<div class="alertInfo"><p></p><i class="iconfont icon-guanbi"></i></div>',
        '<div class="logining"><img src="' + baseUrl + './images/loading.gif">电话功能启动中，请稍后...</div>',
        '<div class="loginfail"><i class="iconfont icon-tanhao"></i>电话条登陆失败</div>',
        '<div class="unknownTip"><span>电话条错误提示</span><p>unknownTip</p><i class="iconfont icon-guanbi"></i></div>',
        '<ul class="phonebar">',
        '<li class="speak iconfont icon-wutonghua"></li>',
        '<li class="pho-state" style="margin-left:0px;">',
        '<ul style="width:120px;">',
        '<li style="padding-top:10px;text-align: center;">暂无通话</li>',
        '</ul>',
        '</li>',
        '<li class="phonebarstate">',
        '<p>置忙</p>',
        '<b class="iconfont icon-xiajiantou" id="Changestate" style="padding-left:4px;color:white;"></b>',
        '<span>--:--:--</span>',
        '<ul class="pho-changeState-sub" id="Statelist">',
        '<li><i class="iconfont icon-zaixian"></i><a href="#">置闲</a></li>',
        '</ul>',
        '</li>',
        '<li></li>',
        '<li class="pho-state-change btn_holdon btn_callback"><a href="#" class="font1 baochi">保持</a></li>',
        '<li class="pho-state-change btn_consult">',
        '<a href="#" id="zixun" class="font2">咨询</a>',
        '<ul class="pho-advisory" id="zixunList" style="display:none" >',
        '<li class="pho-bohao-sub1"></li>',
        '<li class="pho-bohao-sub2 pho-advisory-sub2">',
        '<div class="pho-group-line">',
        '<span>',
        '<span class="iconfont icon-weixuanzhong on"></span>',
        '<span class="pho-group-innerline">内线</span>',
        '</span>',
        '<span>',
        '<span class="iconfont icon-weixuanzhong"></span>',
        '<span>外线</span>',
        '</span>',
        '</div>',
        '<ul class="pho-chioces1">',
        '<li class="pho-group">',
        '<div class="scrollbar-inner">',
        '<ul>',
        '<li class="searchStaff">',
        '<i class="iconfont icon-iconfonticonfontsousuo1" @click="searchStaffBtn()"></i>',
        '<input maxlength="11" type="text" placeholder="搜索员工" class="pho-input searchInput">',
        '</li>',
        '</ul>',
        '</div>',
        '</li>',
        '</ul>',
        '<ul class="pho-chioces2">',
        '<!--选择外线时-->',
        '<li></li>',
        '</ul>',
        '</li>',
        '<li class="pho-group-confirm"><a>确定</a></li>',
        '</ul>',
        '</li>',
        '<li class="pho-state-change btn_transfer"><a href="#" class="font3">转接</a></li>',
        '<li class="pho-state-change btn_meet"><a href="#" class="font4">会议</a></li>',
        '<li class="pho-state-change btn_monitor"><a href="#" class="font5">监听</a></li>',
        '<li class="pho-state-change btn_whisper"><a href="#" class="font6">强拆</a></li>',
        '<li class="pho-state-change btn_insert"><a href="#" class="font7">强插</a></li>',
        '<li class="pho-state-change btn_drop"><a href="#" class="font14">密语</a></li>',
        '<li class="pho-state-change btn_cooperation"><a href="#" class="font8">协作</a></li>',
        '<li class="pho-state-change btn_transferIvr" style="width: 45px;"><a href="#" class="font9">转IVR</a></li>',
        '<li class="pho-state-change btn_degree" style="width: 45px;"><a href="#" class="font15">满意度</a></li>',
        '<li class="pho-state-change btn_transferSkill" style="width: 60px;">',
        '<a href="#" class="font12">转技能组</a>',
        '<ul class="pho-advisory" id="skillList" style="display:none" >',
        '<li class="pho-bohao-sub1"></li>',
        '<li class="pho-bohao-sub2 pho-advisory-sub2">',
        '<ul class="pho-chioces1">',
        '<li class="pho-group">',
        '<div class="scrollbar-inner">',
        '<ul>',
        '<li class="searchSkillStaff">',
        '</li>',
        '</ul>',
        '</div>',
        '</li>',
        '</ul>',
        '<li class="pho-group-confirm"><a>确定</a></li>',
        '</ul>',
        '</li>',
        //'<li class="pho-state-change btn_step_meet" style="width: 60px;"><a href="#" class="font13">单步会议</a></li>',
        '<li class="pho-state-change btn_startmute" style="width: 60px;"><a href="#" class="font10">静音</a></li>',
        //'<li class="pho-state-change btn_endmute" style="width: 60px;"><a href="#" class="font11">结束静音</a></li>',
        '<li class="iconfont icon-chongzhi1 pho-chongzhi-li">',
        '<ul class="pho-chongzhi">',
        '<li>重置</li>',
        '<li class="setOnCall">设置</li>',
        '</ul>',
        '</li>',
        '<li style="position: absolute;right:0px;top:44px;" class="callSetting">',
        '<div class="setUp">',
        '<div class="setUpTitle">设置<i class="iconfont icon-guanbi"></i></div>',
        '<div class="setUpConfigure" style="position: relative;">',
        '<div class="automaticResponse">',
        '<span style="color:#4f5866;display:block;padding:10px 0px 10px 20px;">主叫号码</span>',
        '<span style="border-radius: 0px;margin-left:34px;margin-bottom:10px;" class="iconfont icon-weixuanzhongduoxuan"></span><span>启用主叫号码</span>',
        '</div>',
        '<div class="callingNumberBox">',
        '<input class="callingNumber" type="text" readonly="value"/>',
        '<ul class="callingNumberList">',
        '</ul>',
        '</div>',
        '<button style="position: absolute;right: 60px;bottom: 10px;outline:none;background:#49CC81;width:40px;height:24px;border:none;border-radius:4px;color:white;font-size:12px;cursor: pointer;" class="Determine">确定</button>',
        '<button style="position: absolute;right: 10px;bottom: 10px;outline:none;background:#4f5866;width:40px;height:24px;border:none;border-radius:4px;color:white;font-size:12px;cursor: pointer;" class="Unset">取消</button>',
        '</div>',
        '</div>',
        '</li>',
        '</div>'
    ];
    phoarray = phoarray.join('');
    $("body").append(phoarray);
    /*
     * 初始化位置
     */
    var posiX = userInfo.positionX;
    var posiY = userInfo.positionY;
    $('.phonebar').css({
        'position': 'absolute',
        'top': posiX + 'px',
        'left': posiY + 'px'
    })
    $('.logining').css({
        'position': 'absolute',
        'top': posiX + 'px',
        'left': posiY + 'px'
    })
    $('.loginfail').css({
        'position': 'absolute',
        'top': posiX + 'px',
        'left': posiY + 'px'
    })
    $('.unknownTip').css({
        'position': 'absolute',
        'right': 30 + 'px',
        'top': posiX + 'px'
    })
    /*
     * 页面初始状态
     */
    var $phoarraybox = $('.phoarraybox');
    var $alertInfo = $('.alertInfo');
    var $logining = $('.logining');
    var $loginfail = $('.loginfail');
    var $unknownTip = $('.unknownTip');
    var $phonebar = $('.phonebar');
    var $zixunList = $('#zixunList');
    var $statelist = $('.Statelist')
    var $advisoryHead = $zixunList.find('.pho-bohao-sub1') // 咨询面板头部
    var $settingPanel = $('.pho-chongzhi'); //设置重置面板
    var $callSetting = $('.callSetting') //主叫号码面板
    var $callingNumberList = $('.callingNumberList'); //主叫号码列表
    var $callingNumber = $('.callingNumber'); //已选主叫号码
    var $skillList = $('#skillList');
    $phoarraybox.show();
    $alertInfo.hide();
    $logining.hide();
    $loginfail.hide();
    $unknownTip.hide();
    $settingPanel.hide();
    $statelist.hide();
    $phonebar.hide();
    window.$phoarraybox = $phoarraybox;
    // 电话条全部隐藏
    function phoneAllHide() {
        console.log('*********************************************')
        console.log('调用了all隐藏')
        $phoarraybox.hide();
        $alertInfo.hide();
        $logining.hide();
        $loginfail.hide();
        $unknownTip.hide();
        $settingPanel.hide();
        $statelist.hide();
        $phonebar.hide();
    }
    window.phoneAllHide = phoneAllHide
    /*
     * 初始化参数变量
     */
    var explicitNum = ''; //外显号码
    phone.config.explicitNum = explicitNum;
    var showType = ''; //0 咨询 2监听
    var targetNum, conferenceParty;
    /*
     * 将服务器收到的msg转为树形结构对象
     */
    function msg2Tree(msg) {
        var emps = msg.slice(0, -1).split("|");
        var hash = {};
        for (var i = 0; i < emps.length; i++) {
            var emp = emps[i];
            var fields = emp.split(":");
            if (fields.length > 1) {
                var groups = fields[1].slice(0, -1).split(";");
                for (var j = 0; j < groups.length; j++) {
                    var gname = groups[j];
                    hash[gname] = (hash[gname] || []).concat({
                        eid: fields[0],
                        ename: fields[2]
                    });
                }
            }
        }
        return hash;
    }
    /*
     * 将树形结构对象生成ul下的多个li html片段
     */
    function tree2html(tree) {
        var html = "";
        for (var key in tree) {
            var li = [
                '<li>',
                '<b class="iconfont icon-xiajiantou" style="cursor:pointer;" data-group="xiajiantou"></b>',
                '<span class="iconfont icon-weixuanzhong on" data-choice="xuanxiang" style="display:none"></span>',
                '<span class="skillGroupName">' + key + '</span>',
                '<ul data-group="phon-group">'
            ];
            var emps = tree[key];
            for (var i = 0; i < emps.length; i++) {
                var emp = emps[i];
                li = li.concat([
                    '<li>',
                    '<span class="iconfont icon-weixuanzhong"></span>',
                    // '<span style="margin-right:10px;">工号  <span></span></span>',
                    '<span>' + emp.ename + '(<span data-eid="eid">' + emp.eid + '</span>)</span>',
                    '</li>'
                ])
            }
            li = li.concat([
                '</ul>',
                '</li>',
            ]);
            html += li.join("");
        }
        return html;
    }

    //员工搜索
    $(".searchStaff>input:text").keyup(function () {
        console.log('输入内容', $(this).val())
        searchInTree($(this).val());
    })

    function searchInTree(kw) {
        var parentUlSelector = "#zixunList";
        kw = kw.replace(/^\s+|\s+$/g, "");
        console.log('kw=  ', kw)
        if (kw.length == 0) {
            console.log('kw.length==0');
            $('.searchStaff').nextAll().find('[data-group=phon-group]').find('li').show();
            $('.searchStaff').nextAll().find('[data-group=phon-group]').find('li').css('display', 'block');
            console.log('ll2', $('.searchStaff').nextAll().find('[data-group=phon-group]'))
        } else {
            console.log('kw.length:', kw.length);
            var chooseKw = 'li:contains(' + kw + ')';
            var notChooseKw = 'li:not(:contains(' + kw + '))'
            $('.searchStaff').nextAll().find('[data-group=phon-group]').find(chooseKw).css('display', 'block');
            $('.searchStaff').nextAll().find('[data-group=phon-group]').find(notChooseKw).css('display', 'none');
        }
    }

    /*
     * 按钮事件 显示置闲置忙面板
     * 切换置闲置忙状态
     */
    $phonebar.on('click', '.phonebarstate', function (e) {
        $("#Statelist.pho-changeState-sub").toggle();
    })
    $("#Statelist.pho-changeState-sub").on("click", "li", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var targetTxt = $(this).children("a").text();
        var curStatus = $('.phonebarstate>p').text();
        var that = this;
        if ($(this).data('type') === 'self') { // 点击是自己写入的置忙 ，非小状态
            phone.defineEvent('btn_notready');
        } else if (targetTxt === '置闲') { //点击是置闲
            if (curStatus !== '置闲') {
                phone.defineEvent('btn_ready');
            }
        } else if (targetTxt !== '置闲') { // 点击的是小状态下的置忙
            var statusText = $(this).attr('data-statusCode');
            phone.changeSmallStatus(statusText, function (res) {
                // 应该要去调置忙 接口
                if (res.status === '0') {
                    $(that).siblings().show();
                    $(that).hide();
                    $('.phonebarstate').find('p').text(targetTxt);
                    curNotReadyTxt = targetTxt;
                    if (curStatus === '置闲' || curStatus === '整理') {
                        phone.defineEvent('btn_notready');
                    }
                }
            }); // 事件切换
        }
        $(".pho-changeState-sub").hide();
    });
    /*
     * 挂断事件
     * 接听事件
     */
    $phonebar.on("click", "li:nth-child(1).icon-guaduan.allowed", function () {
        phone.defineEvent('btn_disconnect');
        $('.pho-input').val('');
        // $(this).css('cursor','not-allowed');
        $(this).removeClass('allowed').addClass('not-allowed');
    }).on("click", "li:nth-child(1)>img", function () {
        phone.defineEvent('btn_answer');
    });
    /*
     * 开始静音
     */
    $phonebar.on("click", ".pho-state-change.calling>.font10", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_startmute');
    })

    /*
     * 结束静音
     */
    $phonebar.on("click", ".pho-state-change.calling>.font11", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_endmute');
    })

    /*
     * 转IVR
     */
    $phonebar.on("click", ".pho-state-change.calling>.font9", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_step_meet');
    })

    /*
     * 转技能组
     */
    $phonebar.on("click", ".pho-state-change.calling>.font12", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var $skillHead = $skillList.find('.pho-bohao-sub1') // 咨询面板头部
        $skillList.toggle();
        var display = $skillList.css('display');
        if (display === 'block') {
            showType = 0;
            $skillHead.html('转技能组<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>')
            phone.ucObj.doGetSkillList(function (data) {
                if (data.Code == "0") {
                    var skillName = [];
                    skillName = data.Msg.split(';');
                    var html = treeSkillhtml(skillName);
                    var $li_first = $(".searchSkillStaff");
                    $li_first.siblings().remove(); //先删除第一个li的所有兄弟
                    $li_first.after(html); //再在第一个li后追加tree2html()生成的HTML代码片段
                }
            });
        }
    })

    /*
     * 将树形结构对象生成ul下的多个li html片段
     */
    function treeSkillhtml(skillList) {
        var html = "";
        html += '<li class="clickSkillStaff">';
        html += '<ul data-group="phon-group">';
        skillList.forEach(function (item) {
            if (item === '' || item === 'undefined') {
                return true;
            }
            var li = [
                '<li>',
                '<span class="iconfont icon-weixuanzhong"></span>',
                // '<span style="margin-right:10px;">工号  <span></span></span>',
                '<span data-eid="eid" class="nocheck">' + item + '</span>',
                '</li>'
            ];
            html += li.join("");
        })
        html += '</li>';
        html += '</ul>';
        return html;
    }

    /*
     * 保持事件
     * 接回事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font1", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var text = $(this).html();
        if (text === "保持") {
            phone.defineEvent('btn_holdon');
        } else if (text === "接回") {
            phone.defineEvent('btn_callback');
        }
    })

    /*
    显示咨询面板
     */
    function doGetAgent(showType) {
        phone.ucObj.doGetAgent(showType, function (data) {
            if (data.Code == "0") {
                // 模拟数据
                var tree = msg2Tree(data.Msg); //将服务器收到的msg转为树形结构对象
                //var tree = msg2Tree('30006:业务咨询;:胡静::24|');//将服务器收到的msg转为树形结构对象
                var html = tree2html(tree); //将树形结构对象生成ul下的多个li html片段
                var $li_first = $(".searchStaff");
                $li_first.siblings().remove(); //先删除第一个li的所有兄弟
                $li_first.after(html); //再在第一个li后追加tree2html()生成的HTML代码片段
            }
        });
    }
    $phonebar.on("click", ".pho-state-change.calling>.font2", function (e) {
        e.stopPropagation();
        e.preventDefault();
        $zixunList.toggle();
        var display = $zixunList.css('display');
        if (display === 'block') {
            showType = 0;
            $advisoryHead.html('咨询<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>')
            doGetAgent(showType);
            $('.pho-chongzhi-li>.pho-chongzhi,.pho-changeState>.pho-changeState-sub,.pho-panel>.pho-bohaopan').hide();
        }
    })
    //     //员工搜索
    //     $('.searchInput').click(function(){
    // // $(".searchStaff>searchInput").keyup(function(){
    // // $(".searchStaff>input:text").keyup(function(){
    //         console.log('searchStaff keyup')
    //         searchInTree($(this).val());
    //       })
    //       function searchInTree(kw){
    //         var parentUlSelector="#zixunList";
    //         kw=kw.replace(/^\s+|\s+$/g,"");
    //         if(kw.length==0){
    //           $('.searchStaff').next().find('[data-group=phon-group]').find('li').show();
    //           console.log($('.searchStaff').next().find('[data-group=phon-group]'))
    //         }else{ var chooseKw = 'li:contains('+kw+')';
    //           $('.searchStaff').next().find('[data-group=phon-group]').find(chooseKw).show();
    //         }
    // }
    /*
     *转接事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font3", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_transfer');

    })

    /*
     *会议事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font4", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_meet');
    })

    /*
     *单步会议
     */
    $phonebar.on("click", ".pho-state-change.calling>.font13", function (e) {
        e.stopPropagation();
        e.preventDefault();
        $zixunList.toggle();
        var display = $zixunList.css('display');
        if (display === 'block') {
            showType = 3;
            $advisoryHead.html('单步会议<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>')
            doGetAgent(showType);
        }
    })

    /*
     *监听显示
     */
    $phonebar.on("click", ".pho-state-change.calling>.font5", function (e) {
        e.stopPropagation();
        e.preventDefault();
        $zixunList.toggle();
        var display = $zixunList.css('display');
        if (display === 'block') {
            showType = 2;
            $advisoryHead.html('监听<span class="iconfont icon-guanbi" data-guanbi="zixun"></span>');
            doGetAgent(showType);
        }
    })
    /*
     *强拆事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font6", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_drop')
    })
    /*
     *强插事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font7", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_insert')
    })
    /*
     *密语事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font14", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_whisper')
    })
    /*
     *满意度事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font15", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_degree')
    })
    /*
     *协作事件
     */
    $phonebar.on("click", ".pho-state-change.calling>.font8", function (e) {
        e.stopPropagation();
        e.preventDefault();
        phone.defineEvent('btn_cooperation')
    })
    /*
     *拨号事件
     * 首先选择主叫号码
     */
    $('.Determine').click(function () {
        if ($('.automaticResponse .icon-weixuanzhongduoxuan').hasClass('on')) { //请用主叫号码
            explicitNum = 'tel:' + $('.callingNumber').val();
            phone.config.explicitNum = explicitNum;
            if (explicitNum == '') {
                alert('请选择外显号')
            } else {
                $callSetting.hide();
            }
        } else {
            explicitNum = '';
            phone.config.explicitNum = explicitNum;
            $callSetting.hide();
        }
    })
    $(".phonebar>li:nth-child(4)").phopanel("panel1", phone, explicitNum);
    $(".pho-chioces2>li").phopanel("panel2", phone, explicitNum);
    /*
     *关闭咨询面板事件
     */
    $phonebar.on("click", ".pho-advisory .icon-guanbi", function (e) {
        e.stopPropagation();
        e.preventDefault();
        $zixunList.hide();
        $skillList.hide();
    })
    /*
     *设置及重置面板事件
     * 面板显隐
     */
    $phonebar.on("click", ".pho-chongzhi-li", function (e) {
        e.stopPropagation();
        e.preventDefault();
        $settingPanel.toggle();
    })
    /*
     *重置事件
     */
    $phonebar.on("click", ".pho-chongzhi:nth-child(1)", function (e) {
        e.stopPropagation();
        e.preventDefault();
        $settingPanel.hide();
        phone.defineEvent('btn_reset')

    })
    /*
     *咨询面板事件
     */
    //一级菜单显示隐藏
    $(".pho-chioces1").on("click", ".pho-group ul>li:not(.searchStaff)", function (e) {
            e.stopPropagation();
            var $li = $(this);
            if ($li.children().first().is(".rotateZ9")) { //现在是收起
                //就展开
                $li.children().first().removeClass('rotateZ9')
                    .next('.icon-weixuanzhong').addClass("on") //开灯
                    .next().next().show();
                //兄弟中的子元素都收起
                $li.siblings(":not(.searchStaff)").children().first('.icon-xiajiantou').addClass('rotateZ9')
                    .next('.icon-weixuanzhong').removeClass("on") //关灯
                    .next().next().hide();
            } else { //如果现在是展开
                //就只关闭自己，不管别人
                $li.children().first().addClass('rotateZ9')
                    .next('.icon-weixuanzhong').removeClass("on")
                    .next().next().hide();
            }
        })
        //二级菜单显示隐藏
        .on("click", "[data-group=phon-group]>li", function (e) {
            e.stopPropagation();
            var $li = $(this);
            if (!$li.children().first().is(".on")) { //只有灭时
                $li.children().first().addClass("on");
                $li.children().last().addClass("checkedSkill");
                $li.siblings().children("span:nth-child(1)").removeClass("on");
                $li.siblings().children("span:nth-child(2)").removeClass("checkedSkill");
            } else {
                $li.children().first().removeClass("on");
                $li.children().last().removeClass("checkedSkill");
            }
        })
    //技能组选择
    $(".clickSkillStaff").on("click", "[data-group=phon-group]>li", function (e) {
        e.stopPropagation();
        var $li = $(this);
        if (!$li.children().first().is(".on")) { //只有灭时
            $li.children().first().addClass("on");
            $li.children().first().attr("id", "checkedSkill");
            $li.siblings().children("span:nth-child(1)").removeClass("on");
        } else {
            $li.children().first().removeClass("on");
            $li.children().first().removeAttr("id");
        }
    })
    /*
     *咨询执行
     */
    function doConsult() {
        if ($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
            var consultType = 3;
            showType = 0;
            if (targetNum.indexOf('sip:') === -1) {
                targetNum = "Tel:" + targetNum;
            }
            phone.defineEvent('btn_consult', {
                'consultType': consultType,
                'targetNum': targetNum
            });
            console.log('执行了外线咨询')
        } else {
            var consultType = 4;
            showType = 0;
            console.log('执行了内线咨询')
            phone.defineEvent('btn_consult', {
                'consultType': consultType,
                'targetNum': targetNum
            });
        }
    }
    /*
     *咨询监听事件
     */
    $zixunList.on("click", ".pho-group-confirm", function (e) { //确定按钮
        e.preventDefault();
        if ($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
            // 外线的电话号码
            targetNum = conferenceParty = $('.pho-chioces2>li>div>input').val();
        } else {
            //工号
            targetNum = conferenceParty = $("[data-group=phon-group]").children().children('.on').siblings().children("[data-eid=eid]").html();
        }
        //根据查询人员列表的参数判断是咨询还是监听
        if (showType === 0) { //0 咨询
            //调用咨询接口
            // phone.defineEvent('btn_consult')
            doConsult();
            $zixunList.hide();
        } else if (showType === 2) { //2 监听
            //调用监听接口
            phone.defineEvent('btn_monitor', {
                'conferenceParty': conferenceParty
            })
            $zixunList.hide();
        } else if (showType === 3) { //3 单步会议
            //调用监听接口
            console.log('main.js start doStepMeeting');
            doStepMeeting();
            $zixunList.hide();
        }
    })

    /*
     *转接技能组监听事件
     */
    $skillList.on("click", ".pho-group-confirm", function (e) { //确定按钮
        e.preventDefault();
        //技能组
        var skillGroup = $("[data-group=phon-group]").find('.checkedSkill').text();
        console.log('skillList skillGroup: ' + skillGroup);
        //调用监听接口
        phone.ucObj.doTransferSkill(skillGroup);
        // phone.defineEvent('btn_transferSkill', { 'skillGroup': skillGroup })
        $skillList.hide();
    })


    /*
     *咨询执行
     */
    function doStepMeeting() {
        if ($('.pho-group-line>span:last-child').children('.icon-weixuanzhong').is('.on')) {
            var consultType = 3;
            showType = 0;
            if (targetNum.indexOf('sip:') === -1) {
                targetNum = "Tel:" + targetNum;
            }
            phone.defineEvent('btn_step_meet', {
                'consultType': consultType,
                'targetNum': targetNum
            });
            console.log('执行了外线咨询')
        } else {
            var consultType = 4;
            showType = 0;
            console.log('执行了内线咨询')
            phone.defineEvent('btn_step_meet', {
                'consultType': consultType,
                'targetNum': targetNum
            });
        }
    }

    /*
     *切换内外线事件
     */
    $(".pho-group-line>span:first-child").click(function () {
        $(this).children().first().addClass("on").parent().next().children().first().removeClass("on");
        $(".pho-chioces1").show().next().hide();
    })
    $(".pho-group-line>span:last-child").click(function () {
        $(this).children().first().addClass("on").parent().prev().children().first().removeClass("on");
        $(".pho-chioces2").show().prev().hide();
    })

    /*
     *滚动
     */
    $('.scrollbar-inner').scrollbar();

    /*
     *设置面板
     */
    // 设置面板显示
    $phonebar.on("click", ".setOnCall", function () {
        $callSetting.show();
    })
    // 设置面板关闭
    $('.setUpTitle .icon-guanbi').click(function () {
        $callingNumberList.hide();
        $settingPanel.hide();
        $callSetting.hide();
    })
    // 设置面板取消
    $('.Unset').click(function () {
        $callingNumberList.hide();
        $callSetting.hide();
        $settingPanel.hide();
    })

    $('.automaticResponse').on("click", ".icon-weixuanzhongduoxuan", function () {
        if ($(this).hasClass("on")) {
            $(this).removeClass("on");
            $callingNumber.css("cursor", "not-allowed");
            $callingNumber.val('');
            $callingNumberList.hide();
        } else {
            $(this).addClass("on");
            $callingNumber.css("cursor", "pointer")
        }
    })
    // 主叫 （外显号码列表）显隐
    $callingNumber.click(function () {
        if ($('.automaticResponse .icon-weixuanzhongduoxuan').hasClass("on")) {
            $callingNumberList.toggle();
        } else {
            $callingNumberList.hide();
        }
    });
    // 主叫 （外显号码列表）选择
    $callingNumberList.on("click", "li", function () {
        $callingNumber.val($(this).text());
        $callingNumberList.hide();
    })
    // 电话条提示面板关闭
    $unknownTip.on('click', 'i', function () {
        $unknownTip.hide(500);
    })
})